//
//  HomeViewController.swift
//  TODOApp
//
//  Created by chenyh on 2018/5/25.
//  Copyright © 2018年 chenyh. All rights reserved.
//

import UIKit
import Alamofire

class HomeViewController: UITableViewController {
    static let staticCell = "UITableViewCell"
    fileprivate var datas = [HomeModel]()
    fileprivate var homeProvider = HomeProvider()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        tableViewInit()

        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getTODOList()
    }
    private func tableViewInit(){
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: HomeViewController.staticCell)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return datas.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(ofType: HomeCell.self, at: indexPath)
            cell.homeModel = datas[indexPath.row]
    
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let addContentVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "AddContentViewController") as? AddContentViewController {
            addContentVC.homeModel = datas[indexPath.row]
            self.show(addContentVC, sender: nil)
        }
        
        
    }
    
   private func getTODOList() {
    var configuration   = RequestConfiguration()
        configuration.requestType = .get

    Alamofire.request("http://0.0.0.0:8888/api/v1/home/todos",
                      method: configuration.requestType,
                      parameters: configuration.requestParams,
                      encoding: configuration.requestEncode,
                      headers:configuration.requestHeaderFormat)
        .responseJSON(queue: DispatchQueue.global(qos: .background), options:        JSONSerialization.ReadingOptions.mutableContainers, completionHandler: { [unowned self] (responseObject) in
            printLog(responseObject.description)
            NetLayerRequestSender.kShowOrHideNetworkActivityIndicator(false)
            
            if let error = responseObject.error {
                print(error.localizedDescription)
            }
            if let dict = try? JSONSerialization.jsonObject(with: responseObject.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                
                if dict == nil {
                    return
                }
                guard let result = dict!["result"] as? [[String: Any]] else {
                    return
                }
                
               self.datas =  result.map {
                    HomeModel.deserialize(from: $0)!
                }
                GCD.runOnMainThread {
                    self.tableView.reloadData()
                }
                
                
            }
        }).resume()
    
   }
    
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        var configuration   = RequestConfiguration()
            configuration.requestType = .delete
            configuration.requestParams = ["id": datas[indexPath.row].id] as [String: Any]
        
        
        Alamofire.request("http://0.0.0.0:8888/api/v1/home/delTodoItem",
                          method: configuration.requestType,
                          parameters: configuration.requestParams,
                          encoding: configuration.requestEncode,
                          headers:configuration.requestHeaderFormat)
            .responseJSON(queue: DispatchQueue.global(qos: .background), options:        JSONSerialization.ReadingOptions.mutableContainers, completionHandler: { [unowned self] (responseObject) in
                printLog(responseObject.description)
                NetLayerRequestSender.kShowOrHideNetworkActivityIndicator(false)
                
                if let error = responseObject.error {
                    print(error.localizedDescription)
                }
                if let dict = try? JSONSerialization.jsonObject(with: responseObject.data!, options: .mutableContainers) as? Dictionary<String, Any>,let dictValue = dict,let _ = dictValue["status"] as? Int {
                    
                  
                    if dict == nil {
                        return
                    }
                    guard let result = dict!["result"] as? Bool else {
                        return
                    }
                    if result == true {
                        GCD.runOnMainThread {
                            self.datas.remove(at: indexPath.row)
                            self.tableView.reloadData()
                        }
                    }
                    
                }
            }).resume()
        
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
